package com.server.wx;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.KeyManagerFactory;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.client.config.RequestConfig;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import com.aliyuncs.http.HttpRequest;
import com.config.AppReturn;
import com.config.ConstDefine;
import com.config.ConstService;
import com.fasterxml.jackson.databind.ser.std.StdKeySerializers.StringKeySerializer;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.jfinal.weixin.sdk.utils.JsonUtils;
import com.server.pay.TestPayZS;
import com.util.HttpKit;
import com.util.IOUtil;
import com.util.StrKit;


@Component
public class WxUtil {
	@Autowired
	ConstService constService;
	private String redPackage_url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
	private String qytx_url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
	private String cerPath = ConstDefine.getIftest()==1?"d://test/apiclient_cert.p12":"/www/server/apiclient_cert.p12";//是否需要更换
//	private String cerPath ="d://test/apiclient_cert.p12";//
//	private String appid="wxdf862c942b54dd61";
//	private String mch_id="1613953040";
//	private String paternerKey="d3d3d703b7f10011f00efb8c18b8712a";
	
	
//	private String paternerKey="d3d3d703b7f10011f00efb8c18b8712b";
//	private String backUrl="http://kj.liveshop.com.cn:8080/rewardshop/pay/getTxPayRes";
	
	/**
	 * H5支付信息
	 * @param amount
	 * @return
	 */
	public JSONObject getH5PayMSG(String amount,HttpServletRequest request)
	{
		JSONObject jso=null;
		//查记录参数
		String logid=IOUtil.getId();
		String orderid=IOUtil.getUUID();
		//测试用
		try {
//			String totalFee ="1";
			String totalFee =(int)Double.parseDouble(amount)+"" ;
			
			totalFee="1";
			System.out.println("amount:::"+amount);
			System.out.println("微信统一下单");
			// 第一次加签
			Map params = new HashMap();
			long out_trade_no = System.currentTimeMillis();
			params.put("appid", ConstDefine.getTxAppid());
//			params.put("sub_appid", ConstDefine.appid);
//			params.put("openid", openid);
			params.put("mch_id", ConstDefine.getTxPartner());
			params.put("body", "工圣科技");
			params.put("out_trade_no", orderid);
			params.put("total_fee", totalFee);
//			params.put("openid", "o8w1s5VIjmkTyGAl6RVNXWXVDIzY");
			String ip = IpKit.getRealIp(request);
			if (StrKit.isBlank(ip)) ip = "127.0.0.1";
			params.put("spbill_create_ip", ip);
			params.put("trade_type", PaymentApi.TradeType.MWEB+"");
			params.put("nonce_str", String.valueOf(out_trade_no));       
			params.put("notify_url", ConstDefine.getTxNotify_url_wx());
			String sign = PaymentKit.createSign(params, ConstDefine.getTxPaternerKey());
			params.put("sign", sign);
			String xmlResult = PaymentApi.pushOrder(params);
			Map result = PaymentKit.xmlToMap(xmlResult);
			System.out.println("res : "+result);
			jso = new JSONObject(result);
			jso.put("orderid", orderid);
		} catch (Exception e) {
			jso.put("returnCode", "-1");
			e.printStackTrace();
		}
		System.out.println(jso.toString());
		return jso;
	}
	
	/**
	 * 企业提现到零钱
	 * @param openid
	 * @param amount
	 * @return
	 */
	public JSONObject doTxQY(String openid,String amount)
	{
		JSONObject ret = new JSONObject();
		String bno = IOUtil.getId();
		String no = System.currentTimeMillis()+"";
		String send_name = "恭善";
		String mch_id = ConstDefine.getTxPartner();
		String wxappid = ConstDefine.getTxAppid();
		String key = ConstDefine.getTxPaternerKey();
		Map params = new HashMap();
		params.put("mch_appid", wxappid);
		params.put("mchid", mch_id);
		params.put("nonce_str", no);
		params.put("partner_trade_no", bno);
		params.put("openid", openid);
		params.put("check_name", "NO_CHECK");
		params.put("amount", amount);
		params.put("desc", "余额提现");
		String sign = PaymentKit.createSign(params,key);
		params.put("sign", sign);
		String xml = PaymentKit.toXml(params);
	    String xmlResult = HttpUtils.postSSL(qytx_url, xml, cerPath,mch_id);
	    System.out.println("提现回调："+xmlResult);
//	    //测试返回
	    
//	    String xmlResult = "<xml>"
//	    		+ "<return_code><![CDATA[SUCCESS]]></return_code>"
//	    		+ "<return_msg><![CDATA[]]></return_msg>"
//	    		+ "<mch_appid><![CDATA[wx29445a5af4fe9568]]></mch_appid>"
//	    		+ "<mchid><![CDATA[1551413411]]></mchid>"
//	    		+ "<nonce_str><![CDATA[1681895981658]]></nonce_str>"
//	    		+ "<result_code><![CDATA[SUCCESS]]></result_code>"
//	    		+ "<partner_trade_no><![CDATA[20230419171941153555]]></partner_trade_no>"
//	    		+ "<payment_no><![CDATA[10101125784222304194459663076056]]></payment_no>"
//	    		+ "<payment_time><![CDATA[2023-04-19 17:19:47]]></payment_time>"
//	    		+ "</xml>";
	    
		Map<String, String> resultXML = PaymentKit.xmlToMap(xmlResult);
        String result_code = resultXML.get("result_code");
        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
            ret.put("result", "0");
            ret.put("return_msg", resultXML.get("return_msg"));
        }else{
        	ret.put("result", "1");
        	ret.put("orderId", bno);
        	ret.put("wxId", resultXML.get("payment_no"));
        }
		
		return ret;
	}
	
	/**
	 * 200元提现-零钱红包
	 * @return result :1:成功，0：失败   orderId:订单ID  wxId:微信的sendid
	 */
	public JSONObject doTx200(String openid,String amount)
	{
		JSONObject ret = new JSONObject();
		String bno = IOUtil.getId();
		String no = System.currentTimeMillis()+"";
		String send_name = "恭善";
		String mch_id = ConstDefine.getTxPartner();
		String wxappid = ConstDefine.getTxAppid();
		String key = ConstDefine.getTxPaternerKey();
		Map params = new HashMap();
		params.put("mch_billno", bno);
		params.put("mch_id", mch_id);
		params.put("wxappid", wxappid);
		params.put("send_name", send_name);
		params.put("re_openid", openid);
		params.put("total_amount", amount);
		params.put("total_num", "1");
		params.put("wishing", "恭喜发财");
		params.put("client_ip", "127.0.0.1");
		params.put("act_name", "余额提现");
		params.put("remark", "余额提现");
		params.put("scene_id", "PRODUCT_5");
		params.put("nonce_str", no);
		String sign = PaymentKit.createSign(params,key);
		params.put("sign", sign);
		String xml = PaymentKit.toXml(params);
	    String xmlResult = HttpUtils.postSSL(redPackage_url, xml, cerPath,mch_id);
//	    String xmlResult = "";
//	    //测试返回
//	    xmlResult = "<xml>"
//	    		+ "<return_code><![CDATA[SUCCESS]]></return_code>"
//	    		+ "<return_msg><![CDATA[发放成功]]></return_msg>"
//	    		+ "<result_code><![CDATA[SUCCESS]]></result_code>"
//	    		+ "<err_code><![CDATA[SUCCESS]]></err_code>"
//	    		+ "<err_code_des><![CDATA[发放成功]]></err_code_des>"
//	    		+ "<mch_billno><![CDATA[00002]]></mch_billno>"
//	    		+ "<mch_id><![CDATA[1551413411]]></mch_id>"
//	    		+ "<wxappid><![CDATA[wx29445a5af4fe9568]]></wxappid>"
//	    		+ "<re_openid><![CDATA[o8rljt_03GXPTAQQx2uHwubx7D2s]]></re_openid>"
//	    		+ "<total_amount>100</total_amount>"
//	    		+ "<send_listid><![CDATA[1000041701202304183041232671471]]></send_listid>"
//	    		+ "</xml>";
	    
		Map<String, String> resultXML = PaymentKit.xmlToMap(xmlResult);
		
        String result_code = resultXML.get("result_code");
	    System.out.println("请求提现："+amount+"  提现回调："+xmlResult +" code:"+result_code);
        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
            ret.put("result", "0");
            ret.put("return_msg", resultXML.get("return_msg"));
        }else{
        	ret.put("result", "1");
        	ret.put("orderId", bno);
            ret.put("return_msg", StrKit.isBlank(resultXML.get("return_msg"))?"":resultXML.get("return_msg"));
        	ret.put("wxId", StrKit.isBlank(resultXML.get("send_listid"))?"":resultXML.get("send_listid") );
        }
		
		return ret;
	}
	
	 /* 申请退款
	 * @totalFee 总金额，单位:分
	 * @refundFee 退款金额，单位:分
	 * @return {"transaction_id":"4200001338202112146488407668","nonce_str":"MzFVxknVkZlnpFjS","code":"00","out_refund_no":"tkec3efeeb9e9a48f1bff377676a15408a664","sign":"B886721F6E647DB28B18FA9BA01179A8","return_msg":"OK","mch_id":"1617282504","refund_id":"50301500302021121415353961093","cash_fee":"1","out_trade_no":"ec3efeeb9e9a48f1bff377676a15408a","coupon_refund_fee":"0","refund_channel":"","appid":"wxee5da7fef0095ff1","refund_fee":"1","total_fee":"1","result_code":"SUCCESS","coupon_refund_count":"0","cash_refund_fee":"1","return_code":"SUCCESS"}
	 */
	public JSONObject doRefund(String orderid,String totalFee,String refundFee)
	{
		totalFee=ConstDefine.DF0.format(Double.parseDouble(totalFee));
		refundFee=ConstDefine.DF0.format(Double.parseDouble(refundFee));
		System.out.println("totalFee is :"+totalFee);
		System.out.println("orderid is :"+orderid);
		System.out.println("refundFee is :"+refundFee);
		JSONObject jso=new JSONObject();
//		totalFee ="1";
//		totalFee="1";
//		System.out.println("totalFee:::"+totalFee);
		System.out.println("退款");
		// 第一次加签
		Map params = new HashMap();
		long out_trade_no = System.currentTimeMillis();
		params.put("appid", ConstDefine.getTxAppid());
//		params.put("sub_appid", ConstDefine.appid);
		params.put("mch_id", ConstDefine.getTxPartner());
//		params.put("body", "11");
		params.put("out_trade_no", orderid);
		params.put("total_fee", totalFee);
//		params.put("openid", "o8w1s5VIjmkTyGAl6RVNXWXVDIzY");
//		String ip = IpKit.getRealIp(getRequest());
//		if (StrKit.isBlank(ip)) ip = "127.0.0.1";
		String ip = "127.0.0.1";
		params.put("spbill_create_ip", ip);
//		params.put("trade_type", PaymentApi.TradeType.JSAPI+"");
		params.put("nonce_str", String.valueOf(out_trade_no));       
		params.put("notify_url", ConstDefine.getTxNotify_url_wx());
		params.put("refund_fee", refundFee);
		params.put("out_refund_no", "tk"+orderid+IOUtil.getRandom(3));
//		Map<String, String> map=PaymentApi.refund(params, ConstDefine.getTxPaternerKey(), "d://cert//apiclient_cert.p12");//测试
		Map<String, String> map=PaymentApi.refund(params, ConstDefine.getTxPaternerKey(), "/www/server/apiclient_cert.p12");//正式
		jso=StrKit.map2json_str(map);
		System.out.println("退款结果："+jso.toString());
//		String xmlResult = PaymentApi.pushOrder(params);
//		Map result = PaymentKit.xmlToMap(xmlResult);
//		System.out.println(result);
		//如果第一次加签成功，执行二次加签
		for(String key:map.keySet()){
			System.out.println(key+":"+map.get(key));
		}
		
		
		return jso;
		
	}
	
	/**
	 * 小程序获取微信支付签名,同JS支付
	 * @param amount 单位：分
	 * @param openid
	 * @return "{\"returnCode\":\"00\"," +
					"\"timeStamp\":\"1539312834\",\"signType\":\"MD5\",\"prepay_id\":\"wx12105354013144674e6d09e40715376187\",\"nonceStr\":\"1539312834365\"}"
	 */
	public JSONObject getPayMSG_mini(String amount,String openid)
	{
		JSONObject jso=new JSONObject();
		//查记录参数
		String logid=IOUtil.getId();
		String orderid=IOUtil.getUUID();
		//测试用
		if(1==2){
			return new JSONObject("{\"returnCode\":\"00\"," +
					"\"timeStamp\":\"1539312834\",\"signType\":\"MD5\",\"prepay_id\":\"wx12105354013144674e6d09e40715376187\",\"nonceStr\":\"1539312834365\"}");
		}
		try {
//			String totalFee ="1";
			String totalFee =amount;
//			totalFee="1";
//			System.out.println("totalFee:::"+totalFee);
			System.out.println("微信统一下单");
			// 第一次加签
			Map params = new HashMap();
			long out_trade_no = System.currentTimeMillis();
			params.put("appid", ConstDefine.getTxAppid());
//			params.put("sub_appid", ConstDefine.appid);
			params.put("openid", openid);
			params.put("mch_id", ConstDefine.getTxPartner());
			params.put("body", "11");
			params.put("out_trade_no", orderid);
			params.put("total_fee", totalFee);
//			params.put("openid", "o8w1s5VIjmkTyGAl6RVNXWXVDIzY");
//			String ip = IpKit.getRealIp(getRequest());
//			if (StrKit.isBlank(ip)) ip = "127.0.0.1";
			String ip = "127.0.0.1";
			params.put("spbill_create_ip", ip);
			params.put("trade_type", PaymentApi.TradeType.JSAPI+"");
			params.put("nonce_str", String.valueOf(out_trade_no));       
			params.put("notify_url", ConstDefine.getTxNotify_url_wx());
			String sign = PaymentKit.createSign(params, ConstDefine.getTxPaternerKey());
			params.put("sign", sign);
			String xmlResult = PaymentApi.pushOrder(params);
			Map result = PaymentKit.xmlToMap(xmlResult);
			System.out.println(result);
			String return_code = (String) result.get("return_code");
			String return_msg = (String) result.get("return_msg");
			//如果第一次加签成功，执行二次加签
			if ((StrKit.isBlank(return_code))|| ("SUCCESS".equals(return_code))) 
			{
				//二次签名
				String prepay_id = (String) result.get("prepay_id");
				Map packageParams = new HashMap();
				packageParams.put("appId", ConstDefine.getTxAppid());
				packageParams.put("package", "prepay_id=" + prepay_id);
				packageParams.put("nonceStr", System.currentTimeMillis() + "");
				packageParams.put("timeStamp", System.currentTimeMillis() / 1000L+ "");
				packageParams.put("signType", "MD5");
				String packageSign = PaymentKit.createSign(packageParams, ConstDefine.getTxPaternerKey());
				packageParams.put("sign", packageSign);
				packageParams.put("prepay_id",  prepay_id);
				packageParams.put("returnCode", "00");
//				packageParams.remove("package");//传参是该参数带=号，没法传
				System.out.println("paySign:" + packageSign);
				jso=StrKit.map2json(packageParams);
				jso.put("returnCode", "00");
				jso.put("out_trade_no", orderid);
				
				
				
			}else if ((StrKit.isBlank(return_code))||  !("SUCCESS".equals(return_code))) 
			{
				jso.put("returnCode", "03");
			}
		} catch (Exception e) {
			jso.put("returnCode", "-1");
			e.printStackTrace();
		}
		System.out.println(jso.toString());
		return jso;
	}
	
	/**
	 * 获取签名等信息
	 * @param jsapi_ticket
	 * @param url
	 * @return
	 */
	public Map<String, String> sign(String url) {
		String jsapi_ticket=getJSTicket();
		Map<String, String> ret = new HashMap<String, String>();
		String nonce_str = create_nonce_str();
		String timestamp = create_timestamp();
		String string1;
		String signature = "";

		//注意这里参数名必须全部小写，且必须有序
		string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str
				+ "&timestamp=" + timestamp + "&url=" + url;
//		System.out.println(string1);

		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
//			System.out.println(signature);
		} catch (Exception e) {
			e.printStackTrace();
		}

		ret.put("url", url);
		ret.put("jsapi_ticket", jsapi_ticket);
		ret.put("nonceStr", nonce_str);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);
		System.out.println("nstr:"+nonce_str);
		System.out.println("timestamp:"+timestamp);
		System.out.println("ret:"+ret);
		return ret;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}
	/**
	 * 获取JSTicket
	 * @return
	 */
	public String getJSTicket()
	{
		String ticket=constService.getWxJsTicket();
		if(StrKit.isBlank(ticket))//token�Ѿ�ʧЧ
		{
			JSONObject jso=new JSONObject(HttpKit.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+getAccess_token()+"&type=jsapi"));
			if(jso.has("ticket"))
			{
				ticket=jso.getString("ticket");
				constService.setWxJSTicket(ticket);
				
			}else {//如果获取失败，重新获取token
				jso=new JSONObject(HttpKit.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+getAccess_token_direct()+"&type=jsapi"));
				if(jso.has("ticket"))
				{
					ticket=jso.getString("ticket");
					constService.setWxJSTicket(ticket);
					
				}
			}
		}
		return ticket;
	}
	/**
	 * 获取TOKEN
	 * @return
	 */
	public String getAccess_token()
	{
		String token=constService.getWxToken();
		System.out.println("constServiceTOKEN："+token);
//		Record rec=null;
		if(StrKit.notBlank(token)){
//			JSONObject jso=new JSONObject(token);
//			return(jso.getString("token"));
			return token;
		}
		if(StrKit.isBlank(token))//
		{
			JSONObject jso=new JSONObject(HttpKit.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ConstDefine.getTxAppid()+"&secret="+ConstDefine.getTxAppSecret()));
			System.out.println("腾讯获取TOKEN："+jso);
			if(jso.has("access_token"))
			{
				token=jso.getString("access_token");
				constService.setWxToken(token);
				
			}
		}
		return token;
	}
	/**
	 * 获取TOKEN_直接获取，不去缓存中取，防止两个平台来回申请造成token失效
	 * @return
	 */
	public String getAccess_token_direct()
	{
		String token="";
		JSONObject jso=new JSONObject(HttpKit.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ConstDefine.getTxAppid()+"&secret="+ConstDefine.getTxAppSecret()));
		if(jso.has("access_token"))
		{
			token=jso.getString("access_token");
			constService.setWxToken(token);
			
		}
		return token;
	}
	/**
	 * 获取TOKEN
	 * @return
	 */
	public String getAccess_token_main()
	{
		String token=null;
//		Record rec=null;
		if(StrKit.isBlank(token))//token�Ѿ�ʧЧ
		{
			//���»�ȡ�����Ҵ���CONSTSERVICE��
			JSONObject jso=new JSONObject(HttpKit.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ConstDefine.getTxAppid()+"&secret="+ConstDefine.getTxAppSecret()));
			System.out.println("token:"+jso.toString());
			if(jso.has("access_token"))
			{
				token=jso.getString("access_token");
			}
		}
		
		return token;
	}
	
	/**
	 * 根据code获取用户的openid
	 * @param code
	 * @return
	 */
	public Map<String, String> getOpenidByCode(String code)
	{
		if(code==null)return null;
		
		JSONObject jso=new JSONObject(HttpKit.get("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ConstDefine.getTxAppid()+"&secret="+ConstDefine.getTxAppSecret()+"&code="+code+"&grant_type=authorization_code")) ;
		System.out.println("getWXInfoByCode::"+jso.toString());
		if(jso!=null&&jso.has("openid"))
		{
			Map<String, String> map=new HashMap<String, String>();
			map.put("openid",jso.getString("openid") );
			return map;
		}else
		{
			return null;
		}
	}
	
	/**
	 * 查询分享二维码
	 * @return
	 */
	public JSONObject getQRCode(String key)
	{
		JSONObject data = new JSONObject();
//		Map<String, String> paras = new HashMap<String, String>();
//		paras.put("expire_seconds", "604800");
//		paras.put("action_name", "QR_SCENE");
		
		
		JSONObject req = new JSONObject();
		req.put("expire_seconds", 604800);
		req.put("action_name", "QR_STR_SCENE");
		if(StrKit.notBlank(key))
		{
			JSONObject scene = new JSONObject();
			scene.put("scene", new JSONObject().put("scene_str", key));
			req.put("action_info", scene);
		}
		String res = HttpKit.post("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+getAccess_token(), req.toString());
		System.out.println(res);
		data=new JSONObject(res);
		
		return data;
	}
	
	/**
	 * 根据code获取用户的详细信息，
	 * @param code 
	 * @return openid  nickname  headimgurl
	 */
	public Map<String, String> getWXInfoByCode(String code)
	{
		if(code==null)return null;
		
//		if(ConstDefine.getIftest()==1)
//		{
//			Map<String, String> map=new HashMap<String, String>();
//			map.put("openid","123");
//			map.put("nickname","����");
//			map.put("headimgurl", "");
//			return map;
//		}
		
		JSONObject jso=new JSONObject(HttpKit.get("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ConstDefine.getTxAppid()+"&secret="+ConstDefine.getTxAppSecret()+"&code="+code+"&grant_type=authorization_code")) ;
		System.out.println("getWXInfoByCode::"+jso.toString());
		if(jso!=null&&jso.has("openid"))
		{
			String openid=jso.getString("openid");
			String accToken=jso.getString("access_token");
			JSONObject jso_user=new JSONObject(HttpKit.get("https://api.weixin.qq.com/sns/userinfo?access_token="+accToken+"&openid="+openid+"&lang=zh_CN")) ;
			System.out.println("jso_user:"+jso_user.toString());
			if(jso_user!=null&&jso_user.has("nickname"))
			{
				Map<String, String> map=new HashMap<String, String>();
				map.put("openid",jso_user.getString("openid") );
				map.put("nickname", jso_user.getString("nickname"));
				map.put("headimgurl", jso_user.getString("headimgurl"));
				return map;
			}else
			{
				return null;
			}
		}else
		{
			return null;
		}
	}
	
	/**
	 * 根据OPENID查询用户的详细信息，
	 * @param openid
	 * @return subscribe 0:没关注公众号，1：关注了
	 */
	public JSONObject getUserInfoByOpenid(String openid)
	{
		JSONObject jso=null;
		if(ConstDefine.getIftest()==1)
		{
			jso=new JSONObject("{\"sex\":0,\"qr_scene\":0,\"nickname\":\"��������\",\"remark\":\"\"," +
					"\"unionid\":\"o68PXwJE4ysAyeuaE_DEPrzpbeNI\",\"qr_scene_str\":\"\",\"city\":\"\",\"country\":\"\",\"subscribe_time\":1518340039,\"province\":\"\",\"subscribe\":\"1\",\"openid\":\"oxxarxOl_Jvm9uJvouuc547rvYHc\",\"language\":\"zh_CN\",\"groupid\":0,\"headimgurl\":\"http://thirdwx.qlogo.cn/mmopen/aTRRicuq7oLx9HKuEmP6gaMic57JuhdHic8G9r9zEDiaNc5zKZic6T2iaZErJ7C44cd6fhurm1nxZqpibTZNv6h5BYMYriaBQP27kEby/132\"}");
		}else
		{
			String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+getAccess_token()+"&openid="+openid+"&lang=zh_CN";
			System.out.println("url:"+url);
			String wxdata = HttpKit.get(url);
			System.out.println("获取用户的wx信息："+wxdata);
			jso=new JSONObject(wxdata);
			if(jso.has("openid"))
			{
				
			}else {//如果获取失败，重新获取token

				jso=new JSONObject(HttpKit.get("https://api.weixin.qq.com/cgi-bin/user/info?access_token="+getAccess_token_direct()+"&openid="+openid+"&lang=zh_CN"));
				
			}
			
		}
		return jso;
	}
	/**
	 * 增加菜单
	 */
	public void addMenu()
	{
		String postUrl="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+getAccess_token_main();
		JSONObject jso=new JSONObject();
		JSONObject jsomenu=new JSONObject();
		JSONArray jso_buts=new JSONArray();
		//jso_buts.put(new JSONObject().put("type", "click").put("name", "�����̳�").put("key","V1002_TODAY_MUSIC"));
//		jso_buts.put(new JSONObject().put("type", "view").put("name", "进入商城").put("url", "https://www.hljget.com/shop_zasp/appUser/shopOpen/index"));
		
		JSONArray jsarr_menu=new JSONArray();//
		jsarr_menu.put(new JSONObject().put("type", "view").put("name", "臻艾尚品").put("url","http://www.hljget.com/shop_zasp/appUser/shopOpen/goGoodsClass/1"));
		jsarr_menu.put(new JSONObject().put("type", "view").put("name", "爆款集合").put("url","http://www.hljget.com/shop_zasp/appUser/shopOpen/goGoodsClass/2"));
		jsarr_menu.put(new JSONObject().put("type", "view").put("name", "匠心神器").put("url","http://www.hljget.com/shop_zasp/appUser/shopOpen/goGoodsClass/3"));
		jsarr_menu.put(new JSONObject().put("type", "view").put("name", "刚需超市").put("url","http://www.hljget.com/shop_zasp/appUser/shopOpen/goGoodsClass/4"));
		jso_buts.put(new JSONObject().put("name", "产品中心").put("sub_button",jsarr_menu));
		jso_buts.put(new JSONObject().put("type", "view").put("name", "我的管理").put("url", "https://www.hljget.com/shop_zasp/appUser/userCenter/goUCIndex"));
		jso_buts.put(new JSONObject().put("type", "view").put("name", "点击支付").put("url", "https://www.hljget.com/shop_zasp/pay/goPayTest"));
		
		
		//�����˵�
//		JSONArray jsarr_menu=new JSONArray();//�����˵�
//		jsarr_menu.put(new JSONObject().put("type", "click").put("name", "��Ҫǩ��").put("key","V1002_TODAY_MUSIC"));
//		jsarr_menu.put(new JSONObject().put("type", "view").put("name", "ǩ��ǽ").put("url", "http://temp.xiaodaomi.com/weixin/user/qdq").put("key","V1003_TODAY_MUSIC"));
//		jso_buts.put(new JSONObject().put("name", "ǩ��").put("sub_button",jsarr_menu));
//		
////		jso_buts.put(new JSONObject().put("type", "click").put("name", "ǩ��").put("key","V1002_TODAY_MUSIC"));
////		jso_buts.put(new JSONObject().put("type", "view").put("name", "�ͻ�����").put("url", "http://www.lepinyongche.com").put("key","V1003_TODAY_MUSIC"));
//		JSONArray jsarr_menu2=new JSONArray();//�����˵�
//		jsarr_menu2.put(new JSONObject().put("type", "view").put("name", "ף��ǽ").put("url", "http://temp.xiaodaomi.com/weixin/user/qdq"));
//		jsarr_menu2.put(new JSONObject().put("type", "view").put("name", "��ף��").put("url", "http://temp.xiaodaomi.com/weixin/user/qdq"));
//		jso_buts.put(new JSONObject().put("name", "�������").put("sub_button",jsarr_menu2));
		
		
		
		
//		jsarr_menu.put(new JSONObject().put("type", "view").put("name", "�������").put("url", "http://u1684337.viewer.maka.im/k/P5SKG2YN?from=timeline"));
//		jsarr_menu.put(new JSONObject().put("type", "view").put("name", "��ѵ����").put("url", "http://u1684337.viewer.maka.im/k/XN2UAUZV"));
		jso.put("button", jso_buts);
//		jsomenu.put("is_menu_open", 1);
//		jsomenu.put("selfmenu_info", jso);
		System.out.println("jso :::::;"+jso.toString());
		
		
//		String menu="{\"is_menu_open\": 1, \"selfmenu_info\": " +
//				"{\"button\": [{\"type\": \"click\", \"name\": \"���ո���\", \"key\": \"V1001_TODAY_MUSIC\"}, " +
////				"{\"name\": \"�˵�\", \"sub_button\": " +
////				"{\"list\": [{\"type\": \"view\", \"name\": \"����\", \"url\": \"\"}, " +
////				"{\"type\": \"click\", \"name\": \"��һ������\", \"key\": \"V1001_GOOD\"}]} }]}}, " +
//				"\"type\": \"text\", \"key\": \"001\"}]}";
		System.out.println(jsomenu.toString());
		doDataPost(jso.toString(), postUrl);
	}
	
	public static String doDataPost(String obj,String postUrl) { 
//    	String token="JV41J3BBH4uNGphqPkcdgVZs-sCLNmDUPMStwFo17Ymvusq8zPKPPt7MjinuFxnCwSy3bd7mObScse8_r_Xc_TVDsrjJDCXXPyJ-Yqbb3xDnGkGycRdoLEn_KQxFTLGoAAThACADDW";
//    	String ADD_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token; 
    	String res="";
    	try { 
            //�������� 
            URL url = new URL(postUrl); 
            HttpURLConnection connection = (HttpURLConnection) url 
                    .openConnection(); 
            connection.setDoOutput(true); 
            connection.setDoInput(true); 
            connection.setRequestMethod("POST"); 
            connection.setUseCaches(false); 
            connection.setInstanceFollowRedirects(true); 
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
            connection.connect(); 

            //POST���� 
            DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 
            out.write(obj.toString().getBytes("utf-8")); 
            out.flush(); 
            out.close(); 

            //��ȡ��Ӧ 
            BufferedReader reader = new BufferedReader(new InputStreamReader( 
                    connection.getInputStream())); 
            String lines; 
            StringBuffer sb = new StringBuffer(""); 
            while ((lines = reader.readLine()) != null) { 
                lines = new String(lines.getBytes(), "utf-8"); 
                sb.append(lines); 
            } 
            res=sb.toString();
            System.out.println(sb); 
            reader.close(); 
            // �Ͽ����� 
            connection.disconnect(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        }
    	return res;
    } 
	
	
	/**
	 * ��ȡȫ����ע΢�źŵķ�˿
	 */
	public void getAllWXUser()
	{
		JSONObject jso=new JSONObject(HttpKit.get("https://api.weixin.qq.com/cgi-bin/user/get?access_token="+getAccess_token()));
		System.out.println(jso.toString());
//		if(jso.toString().contains("oxxarxOl_Jvm9uJvouuc547rvYHc"))System.out.println("ccccccccccccccc");
//		System.out.println(jso.toString());
	}
	
	
	public String getPhone(String encryptedData,String iv,String session_key)
	{
//		byte[] encrypData = Base64Utils.decodeFromString(encryptedData);
//		byte[] ivData = Base64Utils.decodeFromString(iv);
//		byte[] sessionKey = Base64Utils.decodeFromString(session_key);
//		String resultString = null;
//		AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
//		SecretKeySpec keySpec = new SecretKeySpec(sessionKey, "AES");
//		try {
//			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
//			cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
//			resultString = new String(cipher.doFinal(encrypData), "UTF-8");
//		} catch (Exception e) {
//			e.printStackTrace();
//			Cipher cipher;
//			try {
//				cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
//				cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
//				resultString = new String(cipher.doFinal(encrypData), "UTF-8");
//			} catch (Exception e1) {
//				// TODO Auto-generated catch block
//				e1.printStackTrace();
//			}
//		}
		
		try {
	        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
	        params.init(new IvParameterSpec(Base64.getDecoder().decode(iv.getBytes())));
	        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
	        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.getDecoder().decode(session_key.getBytes()), "AES"), params);
	        byte[] decode = WxUtil.decode(cipher.doFinal(Base64.getDecoder().decode(encryptedData.getBytes())));
	        return new String(decode, StandardCharsets.UTF_8);
	    } catch (Exception e) {
	        System.out.println("shibai");
	        return "";
	    }
	}
	
	public void getPhone2(String encryptedData,String iv,String session_key)
	{
		// 被加密的数据
      byte[] dataByte = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(encryptedData);
      // 加密秘钥
      byte[] keyByte = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(session_key);
      // 偏移量
      byte[] ivByte = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(iv);
      try {
          // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
    	  AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivByte);
    	  Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    	  SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
    	  cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
    	  String res= new String(cipher.doFinal(dataByte),"UTF-8");
    	  System.out.println(res);
      } catch (Exception e) {
          e.printStackTrace();
      }
	}
	
	/**
	 * 删除解密后明文的补位字符.
	 *
	 * @param decrypted 解密后的明文
	 * @return 删除补位字符后的明文
	 */
	public static byte[] decode(byte[] decrypted) {
	    int pad = decrypted[decrypted.length - 1];
	    if (pad < 1 || pad > 32) {
	        pad = 0;
	    }
	    return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
	}
	public static void main(String[] args) {
		
		WxUtil wx=new WxUtil();
//		wx.getPayMSG_mini("1", "oJov259uVErxaY5YlKaJcwQ9D3-Q");
//		wx.getQRCode("mwgdxj123");
//		wx.addMenu();
		
		wx.doTx200("o8rljt_03GXPTAQQx2uHwubx7D2s", "100");
//		wx.doTxQY("o8rljt_03GXPTAQQx2uHwubx7D2s", "100");
		
//		String wxdata = HttpKit.get("https://api.weixin.qq.com/cgi-bin/user/info?access_token=67_VYO37HKw-j6A6ExXsBTBH4cdtY9O8vFyraBjlAceFr2ZgEW9yPlxsbQ-2MezT93v2_DsdAiLS4_hBCwtpuwLhfykLXwdUXE1HQZ8wd035EXVXzSC0P2usozGAqgZKKgAFAJUU&openid=o8rljt_03GXPTAQQx2uHwubx7D2s&lang=zh_CN");
//		System.out.println("获取用户的wx信息："+wxdata);
		
//		wx.getAccess_token_main();
//		
//		JSONObject jso_user=new JSONObject(HttpKit.get("https://api.weixin.qq.com/sns/userinfo?access_token="+wx.getAccess_token_main()+"&openid=oJov259LW9vfkpRfRpMVVVIf-g_Y&lang=zh_CN")) ;
//		System.out.println("jso_user:"+jso_user.toString());
////		wx.getOpenIdByCode("031w36000aCDtL1Mk7400J5If03w360f");
//		String data="l8CPNrn9Y8wEA0yQkC4Q15YHfrAeq3CnWRyZdgvyqfefkmPt8wMSwsMvt7G3A0tGy42KYZmNZgeF0y9TpNDt6Rx5d901e5fA4E1PzLwRQUhlA2F56F+UOzbhq7Khi5aYuWZWn5687BI6qc7r0rhPRPx6gYv2fwjFPIU7gCZr3oWbmnhbWsCmWyWpMffFAAAgFmO4oHtPqfiwa/7/Yw80sw==";
//		String iv="rqfPHhWfOomIFUVqOWGkYQ==";
//		String session_key="6bOujGX5X3Cyk/fmtzbumQ==";
//		String phone = wx.getPhone(data, iv, session_key);
//		System.out.println(phone);

//		wx.getPhone2(data, iv, session_key);
//		Map<String, String> map = wx.getWXInfoByCode("0619Y4000cpEtL15nT200EOBM949Y40Q");
//		for(String key : map.keySet())
//		{
//			System.out.println(key+"="+map.get(key));
//		}
//		System.out.println(wx.getUserInfoByOpenid("oJov259LW9vfkpRfRpMVVVIf-g_Y"));
//		WxUtil.getIns().getAllWXUser();
//		System.out.println(WxService.getIns().getAccess_token());
//		System.out.println(WxUtil.getIns().getJSTicket());
//		System.out.println(WxUtil.getIns().sign("http://192.168.1.111:8090/redActivity/mobile/pay/wxResult?redPackageId=937f95f879324f73a8d47b1279b9eab5"));
	}

}
